package com.whsxt.aspect;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whsxt.anno.Log;
import com.whsxt.domain.SysLog;
import com.whsxt.domain.SysUser;
import com.whsxt.service.SysLogService;
import com.whsxt.service.SysUserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-14 16:34
 * @Description:
 */
@Aspect
@Component
public class LogAspect {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysLogService sysLogService;


    /**
     * 切面
     *
     * @param joinPoint
     * @return
     */
    @Around(value = "@annotation(com.whsxt.anno.Log)")
    public Object myLogAspect(ProceedingJoinPoint joinPoint) {
        //记录用户的操作
        Object result = null;
        //拿到方法名称    方法签名：
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        //拿到注解
        Log log = signature.getMethod().getAnnotation(Log.class);
        //拿到注解里面的属性
        String operation = log.operation();
        //拿到方法执行时间
        long start = System.currentTimeMillis();
        //执行方法
        try {
            result = joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        long end = System.currentTimeMillis();

        //拿到当前用户的名称
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        SysUser sysUser = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .select(SysUser::getUsername)
                .eq(SysUser::getUserId, Long.valueOf(userId))
        );
        String username = sysUser.getUsername();

        //拿到ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();

        //组装对象
        SysLog sysLog = SysLog.builder().username(username).ip(ip).method(methodName)
                .params(joinPoint.getArgs() == null ? "" : JSON.toJSONString(joinPoint.getArgs()))
                .operation(operation)
                .time(end - start)
                .createDate(new Date())
                .build();

        sysLogService.save(sysLog);
        return result;


    }
}
